﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

using FreeFlow.Administration;
using FreeFlow.WinFormsControls.HelperClasses;

namespace FreeFlowAdministrator
{
  public partial class WorkflowInstanceControl : AdminUserControl
  {
    public WorkflowInstanceControl()
    {
      InitializeComponent();
    }

    private WorkflowInstance instance;
    public void LoadWorkflowInstance(WorkflowInstance instance)
    {
      this.instance = instance;
      guidLabel.Text = instance.Guid.ToString();
      createdLabel.Text = instance.Created.ToString();

      if (instance.GetParent() == null)
      {
        parentLabel.Text = instance.ParentFolderId;
      }
      else
        parentLabel.Text = instance.GetParent().Name;

      trackingGrid.DataSource = null;
      trackingGrid.DataSource = instance.TrackingData;
      trackingGrid.ClearColumns();
      trackingGrid.AddColumn("Time");
      trackingGrid.AddColumn("ActivityName", "Activity name");
      trackingGrid.AddColumn("ActivityType", "Activity type");
      trackingGrid.AddColumn("ExecutionStatus", "Execution status");
      trackingGrid.AddColumn("EventType", "Event type");
      trackingGrid.AddColumn("WorkflowEvent", "Workflow event");
      trackingGrid.AddColumn("UserData", "User data");
      trackingGrid.AutosizeColumns();
      trackingGrid.AutosizeRows();

      UIActionList actionList = new UIActionList();
      actionList.Add("Refresh", "Refresh the workflow instance data",
        new ActionExecuteDelegate(RefreshWorkflowInstance));
      actionList.Add("Delete", "Delete this workflow instance", 
        new ActionExecuteDelegate(DeleteWorkflowInstance));
      if (instance.GetParent() != null)
        actionList.Add("Open parent", "Open this folder's parent",
          new ActionExecuteDelegate(OpenParent));
      uiActionsControl.Actions = actionList;
    }

    private string OpenParent()
    {
      FolderForm folderForm = new FolderForm();
      folderForm.LoadFolder(instance.GetParent());
      folderForm.Show();
      return null;
    }

    private string DeleteWorkflowInstance()
    {
      if (MessageBox.Show("Delete this workflow instance?", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes)
      {
        using (new CursorHandler())
        {
          instance.Delete();
        }
        OnItemDeleted();
        Dispose();
      }
      return null;
    }

    private string RefreshWorkflowInstance()
    {
      instance.Refresh();
      LoadWorkflowInstance(instance);
      return null;
    }
  }
}
